<?php
namespace app\base\controller;

use app\base\model\TeacherModel;
use app\common\base\BasicRest;
use app\common\base\pinyinfirstchar;
use app\common\model\AdminModel;
use app\common\tool\Tool;
use think\Config;
use think\Request;
use thinkcms\auth\model\AuthRoleUser;


class Teacher extends BasicRest
{
    public function __construct()
    {
        parent::__construct();
    }

    #获取所有老师信息
    public function index($title='',$page=1){
        $page_number = Config::get('page_number');
        if($title==''){
            //页数
            $count = TeacherModel::where('IsDeleted',0)->count();
            $pages = $count/$page_number;
            $teacherData = TeacherModel::where('IsDeleted',0)->order('Id desc')->page($page,$page_number)->select();
        }else{
            $map['IsDeleted'] = 0;
            $map['Title'] = ['like',"%$title%"];
            $count = TeacherModel::where($map)->count();
            $pages = $count/$page_number;
            $teacherData = TeacherModel::where($map)->order('Id desc')->page($page,$page_number)->select();
        }
        if($teacherData) return res_success($teacherData,ceil($pages));
        return res_fail('未找到信息');
    }

    #获取单个老师信息
    public function read($id){
        $teacherData = TeacherModel::get($id);
        if($teacherData) return res_success($teacherData);
        return res_fail('未找到信息');
    }

    #新增老师信息
    public function save(Request $request){
        $arr = $request->post();
        $model = new TeacherModel;
        $model->save($arr);
        //创建管理员帐号
        $result = $this->createAdmin($arr,$model->Id);
        if($result) return res_success();
        return res_fail('创建失败');
    }

    #修改老师信息
    public function update(Request $request,$id){
        $data = $request->put();
        unset($data['CreateId']);
        unset($data['CreateTime']);
        unset($data['UpdateId']);
        unset($data['UpdateTime']);
        $model = TeacherModel::find($id);
        $res = $model->save($data);
        if($res!== false) return res_success();
        return res_fail('修改失败');
    }

    #删除老师信息
    public function delete($id){
        $res = TeacherModel::where('Id',$id)->update(['IsDeleted'=>'1']);
        if($res) return res_success();
        return res_fail('删除失败');
    }

    //创建管理员
    public function createAdmin($arr,$id){
        $py = new pinyinfirstchar();
        $name = $py->getInitials($arr['Title']);
        $data['admin_name'] = $name;
        $data['admin_password'] = Tool::get('helper')->getMd5($name);
        $data['login_priv'] = 1;
        $data['role'] = '2';
        $data['teacher_id'] = $id;
        $model = new AdminModel;
        $model->save($data);
        $data2['role_id'] = 2;
        $data2['user_id'] = $model->admin_id;
        $res = AuthRoleUser::create($data2);
        if($res) return true;
        return false;
    }

    //excel导入
    public function doExcel(Request $request){
        $file=$request->file('file');
        $info=$file->move(ROOT_PATH . 'public' . DS .'res');
        $name = $info->getSavename();
        $excelName = ROOT_PATH.'public\res\\'.$name;

        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = \PHPExcel_IOFactory::load($excelName);
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();//取得总行数
        $highestColumn = $sheet->getHighestColumn();//取得总列数

        //循环读取excel文件表头
        $fields = '';
        for($p='A';$p<=$highestColumn;$p++){
            $fields .= iconv('utf-8','gbk',$objPHPExcel->getActiveSheet()->getCell("{$p}1")->getValue()).'\\';//读取单元格
            $fieldsArray = explode("\\",$fields);
            array_pop($fieldsArray);
        }

        //循环读取excel文件数据
        for($k='A';$k<=$highestColumn;$k++){
            $str = '';
            if($k=='C'||$k=='P'){
                for($j=2;$j<=$highestRow;$j++){
                    $str .= iconv('utf-8','gbk',gmdate("Y-m-d", \PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue()))).'\\';//读取单元格
                }
            }else{
                for($j=2;$j<=$highestRow;$j++){
                    $str .= iconv('utf-8','gbk',$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue()).'\\';//读取单元格
                }
            }
            $str = rtrim($str,'\\');
            //函数把字符串分割为数组
            ${$k} = explode("\\",$str);
        }

        //循环向数据库导入数据库
        for($s=0;$s<count($A);$s++){
            $sql = [];
            for($i='A';$i<=$highestColumn;$i++){
                $sql[] = ${$i}[$s];
            }
            $data = array_combine($fieldsArray,$sql);
            $data['SubjectId'] = '['.$data['SubjectId'].']';
            $res = TeacherModel::create($data);
        }
        if($res) return res_success();
        return res_fail('删除失败');
    }
}
